/**
 * Created by Feil.Wang(wangfeilong@xuexibao.cn) on 2015/12/30.
 */
var User = require('../models/User');
module.exports = {
    registerView: function (req, res) {
        res.render('register', {
            title: '注册'
        });
    },
    register: function (req, res) {
        var uname = req.body.uname;
        var upwd = req.body.upwd;
        User.findOne({name: uname}, function (err, doc) {
            if (err) {
                res.send({
                    success: false,
                    messages: "网络异常错误！"
                });
                console.warn(err);
            } else if (doc) {
                res.send({
                    success: false,
                    messages: '用户名已存在'
                });
            } else {
                User.create({
                    name: uname,
                    password: upwd
                }, function (err, doc) {
                    if (err) {
                        res.send({
                            success: false,
                            messages: err
                        });
                        console.warn(err);
                    } else {
                        res.send({
                            success: true,
                            messages: "用户创建成功！"
                        });
                    }
                })
            }
        })
    },
    loginView: function (req, res) {
        res.render('login', {
            title: '登录'
        });
    },
    login: function (req, res) {
        var uname = req.body.uname;
        var upwd = req.body.upwd;
        User.findOne({name: uname}, function (err, doc) {
            if (err) {
                res.send({
                    success: false,
                    messages: "网络异常错误！"
                });
                console.warn(err);
            } else if (!doc) {
                res.send({
                    success: false,
                    messages: "用户不存在！"
                });
            } else {
                if (upwd != doc.password) {
                    res.send({
                        success: false,
                        messages: "密码错误！"
                    });
                } else {
                    req.session.userId = doc._id;
                    req.session.userName = doc.name;
                    console.log(doc._id);
                    res.send({
                        success: true,
                        messages: "登录成功！"
                    });
                }
            }
        })
    },
    logout: function (req, res) {
        req.session.userId = null;
        res.redirect("/");
    }
};